#include "index.h"
#include "router/systemManager/dictionaryManager/dictionarymanager.h"
#include "router/systemManager/menuManager/menumanager.h"
#include "router/systemManager/paramsSet/paramsset.h"
#include "router/systemManager/roleManager/rolemanager.h"
#include "router/systemMonitor/serverMonitor/servermonitor.h"
#include "ui_index.h"

#include <QMouseEvent>
#include <QNetworkReply>
#include <QLabel>
#include <QtCore>
#include <QLayout>
#include <QFileDialog>

#include <router/systemManager/deptManager/deptmanager.h>

Index::Index(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Index)
{
    ui->setupUi(this);
    this->setWindowTitle("郑州司徒末的若依");
    this->setWindowIcon(QIcon(":/image/res/stm.jpg"));
    ui->comboBox_setParam_systemBuiltIn->addItem("1332");
    init();

    //头像点击事件
    ui->label_avator->installEventFilter(this);
    dlg = new QDialog();
    userCenterDlg(dlg);

    //api访问结果为401时，
//    QMetaObject::Connection c = connect(&utils,&Utils::back401,this,[=](){
//        qDebug()<<1;
//        this->close();
//    });

    timer = new QTimer;
    connect(this,&Index::open,timer,[=](){
        timer->start(100);
    });
    connect(this,&Index::stop,timer,[=](){
        timer->stop();
    });
    connect(&utils,&Utils::stateChangeSuccess,this,&Index::on_btn_userManager_refresh_clicked);
    connect(timer,&QTimer::timeout,this,[=](){
        mouseGlobalPos = QCursor::pos();
        QPoint posDlg = dlg->pos();
        if( mouseGlobalPos.x() < posDlg.x() || mouseGlobalPos.y() < posDlg.y() ||
            mouseGlobalPos.x() > posDlg.x() + dlg->width() || mouseGlobalPos.y() > posDlg.y() + dlg->height()){
            emit stop();
            dlg->close();
            this->setCursor(Qt::ArrowCursor);
        }
    });

    //菜单点击事件
    connect(ui->treeWidget,&QTreeWidget::itemClicked,this,[=](){
        treeWidgetClicked();
    });

    //修改头像
    connect(ui->btn_avatar,&QPushButton::clicked,this,[=](){
        btn_uploadAvatar_clicked();
    });

    //邮箱正则验证
    QRegExp expEmail("[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\\.[a-zA-Z]+");
    QRegExpValidator *rvalEmail = new QRegExpValidator(expEmail);
    ui->lineEdit_email->setValidator(rvalEmail);
    //手机号正则验证
    QRegExp expPhone("^1[3-9]\\d{9}$");
    QRegExpValidator *rvalPhone = new QRegExpValidator(expPhone);
    ui->lineEdit_phone->setValidator(rvalPhone);

    //菜单弹窗
    treeWidget = new QTreeWidget;
    treeWidget->setHeaderHidden(1);
    treeWidget->setWindowTitle("郑州司徒末");
    treeWidget->setWindowIcon(QIcon(":/image/res/stm.jpg"));
    treeWidget->close();
    connect(treeWidget,&QTreeWidget::clicked,this,[=](){
        routerJump(treeWidget->currentItem());
    });

    //userManager模块
    //初始密码
    initPassword = userManager.getInitPassword();
    //限制输入数字
    ui->lineEdit_userManager_gotoPage->setValidator(new QIntValidator(ui->lineEdit_userManager_gotoPage));
    //图标
    QPixmap pix(":/image/res/search.jpg");
    pix.scaled(25,25);
    ui->label_userManager_deptName->setPixmap(pix.scaled(25,25));
    ui->btn_userManager_hideSearch->setIcon(pix);
    ui->btn_userManager_search->setIcon(pix);
    QPixmap freshPix(":/image/res/refresh.jpg");
    ui->btn_userManager_reset->setIcon(freshPix.scaled(25,25));
    ui->btn_userManager_refresh->setIcon(freshPix.scaled(25,25));
    ui->btn_userManager_isHideColumn->setIcon(QPixmap(":/image/res/6.ico").scaled(25,25));
    ui->dateEdit_userManager_endTime->clear();
    ui->dateEdit_userManager_startTime->clear();
    userManagerHideColumnDlg = new UserManagerHideColumnDlg(&userManagerTableColumn,ui->tableWidget_userManager);
    userManagerHideColumnDlg->close();
    moreDlg = new QDialog;
}

Index::~Index()
{
    delete ui;
}

//初始化首页
void Index::init()
{
    getRouters();
    getInfo();
    initUserManager();
}

//路由菜单
void Index::getRouters()
{
    QNetworkReply * reply = userApi.getRouters();
    QVariant v = reply->readAll();
    QByteArray info = v.value<QByteArray>();
    QJsonDocument document = QJsonDocument::fromJson(info);
    QJsonObject obj = document.object();
    QJsonValue data = obj.value("data");
    routerArr = data.toArray();

    //首页菜单
    setRouters(routerArr);
    ui->stackedWidget->setCurrentIndex(1);
}

//个人信息
void Index::getInfo()
{
    QNetworkReply *reply = userApi.getInfo();
    QByteArray bytes = reply->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::information(this,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    QJsonArray roles = obj.value("roles").toArray();
    user = utils.getUser(bytes);

    if(user->phonenumber == ""){
        return;
    }

    QString url = user->avatar;

    QNetworkAccessManager *netManager = new QNetworkAccessManager;
    QNetworkReply *avataoReply = netManager->get(QNetworkRequest(url));
    connect(netManager,&QNetworkAccessManager::finished,this,[=](){
        avatar.loadFromData(avataoReply->readAll());
        ui->label_avator->setPixmap(avatar.scaled(62,62));
    });
}

//事件过滤
bool Index::eventFilter(QObject *obj, QEvent *event){
    //mouse button pressed
    if (event->type() == QEvent::MouseButtonPress){
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        if(mouseEvent->button() == Qt::LeftButton){
            if(obj == ui->label_avator){
                QDialog *avatarDlg = new QDialog(this);
                avatarDlg->setFixedSize(avatar.width(),avatar.height());
                QLabel l;
                l.setParent(avatarDlg);
                l.setPixmap(avatar);
                avatarDlg->exec();
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }else if(event->type() == QEvent::Enter){   //鼠标进入标签事件
        this->setCursor(Qt::PointingHandCursor);
        dlg->move(ui->label_avator->mapToGlobal(QPoint(0,0)).x() - 10,
                  ui->label_avator->mapToGlobal(QPoint(0,0)).y() + 60);
        dlg->show();
        return true;
    }else if(event->type() == QEvent::Leave){
        emit open();
        return true;
    }else{
        return QObject::eventFilter(obj, event);
    }
}

//个人中心弹窗
void Index::userCenterDlg(QDialog *dlg)
{

    dlg->setWindowFlag(Qt::FramelessWindowHint);

    dlg->resize(70,40);

    QPushButton *userCenter = new QPushButton(dlg);
    userCenter->setText("个人中心");
    userCenter->resize(40,20);
    QPushButton *exit = new QPushButton(dlg);
    exit->setText("退出登录");
    exit->resize(40,20);

    QVBoxLayout *vBoxLayout = new QVBoxLayout(dlg);
    vBoxLayout->setAlignment(Qt::AlignCenter);
    vBoxLayout->addWidget(userCenter);
    vBoxLayout->addWidget(exit);
    dlg->setLayout(vBoxLayout);

    connect(userCenter,&QPushButton::clicked,this,[=](){
        if(ui->stackedWidget->currentIndex() == 0){
            return;
        }
        ui->label_location->setText("个人中心");
        ui->stackedWidget->setCurrentIndex(0);
        initUserCenter();
    });
    connect(exit,&QPushButton::clicked,this,[=](){
        int flag = QMessageBox::question(this,"提示","确定退出登录吗?",QMessageBox::No | QMessageBox::Yes);
        if(flag == QMessageBox::No){
            return;
        }
        emit logout();
        userApi.logout();
        this->close();
    });
}

//路由菜单点击
void Index::treeWidgetClicked()
{
    QTreeWidgetItem *item = ui->treeWidget->currentItem();
    routerJump(item);
}

//点击窗口外位置关闭窗口
bool Index::event(QEvent *event)
{
    if (event->type() == QEvent::ActivationChange){
        if(QApplication::activeWindow() != treeWidget){
            treeWidget->close();
        }
        if(QApplication::activeWindow() != userManagerHideColumnDlg){
            userManagerHideColumnDlg->close();
        }
        if(QApplication::activeWindow() != moreDlg){
            moreDlg->close();
        }
    }
    return QWidget::event(event);
}

//测试按钮
void Index::on_btn_test_clicked()
{
    qDebug()<<"utils.a";

}

//基本信息按钮
void Index::on_pushButton_baseInfo_clicked()
{
    ui->pushButton_baseInfo->setStyleSheet("color:blue;border:none;");
    ui->pushButton_resetPwd->setStyleSheet("color:black;border:none;");
    ui->stackedWidget_2->setCurrentIndex(0);
}

//重置密码按钮
void Index::on_pushButton_resetPwd_clicked()
{
    ui->pushButton_baseInfo->setStyleSheet("color:black;border:none;");
    ui->pushButton_resetPwd->setStyleSheet("color:blue;border:none;");
    ui->stackedWidget_2->setCurrentIndex(1);
}

//初始化个人中心
void Index::initUserCenter()
{
    QNetworkReply *reply = userApi.profile();
    QByteArray bytes = reply->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(this,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    if(200 != obj.value("code").toInt()){
        QMessageBox::warning(this,"提示",obj.value("msg").toString());
        return;
    }
    user = utils.getUser(bytes);
    if(user->phonenumber == ""){
        return;
    }
    //个人信息
    ui->label_Tusername->setText(user->userName);
    ui->label_Tphone->setText(user->phonenumber);
    ui->label_Temail->setText(user->email);
    QString dept = user->dept.deptName + "/" + obj.value("postGroup").toString();
    ui->label_Tdept->setText(dept);
    QString role = obj.value("roleGroup").toString();
    ui->label_Trole->setText(role);
    ui->label_TcreateTime->setText(user->createTime);

    //基本资料
    ui->lineEdit_nickname->setText(user->nickName);
    ui->lineEdit_phone->setText(user->phonenumber);
    ui->lineEdit_email->setText(user->email);
    if(user->sex == "0"){
        ui->radioButton_boy->setChecked(1);
    }else{
        ui->radioButton_girl->setChecked(1);
    }

    //头像
    ui->btn_avatar->setIconSize(QSize(100,100));
    ui->btn_avatar->setIcon(avatar);
}

//上传头像
void Index::btn_uploadAvatar_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(this,"选择头像",
                        QCoreApplication::applicationDirPath(),tr("Images (*.png *.jpg *.jpeg"));
    if(filePath.isEmpty()){
        return;
    }
    QNetworkReply *reply = userApi.uploadAvatar(filePath);
    QByteArray bytes = reply->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(this,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    if(200 != obj.value("code").toInt()){
        QMessageBox::warning(this,"提示",obj.value("msg").toString());
        return;
    }
    avatar.load(filePath);
    ui->btn_avatar->setIcon(avatar);
    ui->label_avator->setPixmap(avatar.scaled(62,62));
    QMessageBox::warning(this,"提示","修改成功");
}

//递归设置路由菜单
void Index::setRouters(QJsonArray routerArr)
{
    ui->treeWidget->setStyleSheet("font: 12pt 黑体;border:none;");
    for(int i = 0;i< routerArr.size();i++){
        QJsonObject menu = routerArr.at(i).toObject();

        QTreeWidgetItem * menuTitle = new QTreeWidgetItem(ui->treeWidget,
                QStringList(menu.value("meta").toObject().value("title").toString()));
        QString icon = menu.value("meta").toObject().value("icon").toString().toLower();
        if(icon != "#"){
            menuTitle->setIcon(0,QIcon(":/svg/res/svg/" + icon + ".svg"));
        }
        QJsonArray menuChildren = menu.value("children").toArray();
        setTreeRouters(&menuChildren,menuTitle);
    }
}

//递归设置弹窗路由菜单
void Index::setTreeRouters(QJsonArray *treeList,QTreeWidgetItem *menu)
{
    for(int i = 0;i< treeList->size();i++){
        QJsonObject obj = treeList->at(i).toObject();
        QTreeWidgetItem *childmenu = new QTreeWidgetItem(menu,
            QStringList(obj.value("meta").toObject().value("title").toString()));
        QString icon = obj.value("meta").toObject().value("icon").toString().toLower();
        if(icon != "#"){
            childmenu->setIcon(0,QIcon(":/svg/res/svg/" + icon + ".svg"));
        }
        QJsonArray arr = obj.value("children").toArray();
        setTreeRouters(&arr,childmenu);
    }
}

//保存基本信息
void Index::on_pushButton_saveBaseInfo_clicked()
{
    if(!ui->label_phoneCheck->text().isEmpty() || !ui->label_emailCheck->text().isEmpty()){
        return;
    }
    user->nickName = ui->lineEdit_nickname->text();
    user->phonenumber = ui->lineEdit_phone->text();
    user->email = ui->lineEdit_email->text();
    user->sex = ui->radioButton_boy->isChecked() == 1 ? "0" : "1";

    QNetworkReply *reply = userApi.updatePersonalInfo(user);
    QByteArray bytes = reply->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(this,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    QMessageBox::information(this,"提示",obj.value("msg").toString());
}

//电话输入框
void Index::on_lineEdit_phone_textChanged(const QString &arg1)
{
    ui->label_Tphone->setText(arg1);
    int pos = 0;
    const QValidator *v = ui->lineEdit_phone->validator();
    QString str = arg1;
    if (v->validate(str, pos) != QValidator::Acceptable)
    {
        ui->label_phoneCheck->setText(QString::fromLocal8Bit("手机号码格式不正确"));
        ui->label_phoneCheck->setStyleSheet("color:red;");
        ui->lineEdit_phone->setStyleSheet("border:1px solid red;");
    }else{
        ui->label_phoneCheck->setText(QString::fromLocal8Bit(""));
        ui->label_phoneCheck->setStyleSheet("");
        ui->lineEdit_phone->setStyleSheet("");
    }
}

//邮箱输入框
void Index::on_lineEdit_email_textChanged(const QString &arg1)
{
    ui->label_Temail->setText(arg1);
    int pos = 0;
    const QValidator *v = ui->lineEdit_email->validator();
    QString str = arg1;
    if (v->validate(str, pos) != QValidator::Acceptable)
    {
        ui->label_emailCheck->setText(QString::fromLocal8Bit("邮箱格式不正确"));
        ui->label_emailCheck->setStyleSheet("color:red;");
        ui->lineEdit_email->setStyleSheet("border:1px solid red;");
    }else{
        ui->label_emailCheck->setText(QString::fromLocal8Bit(""));
        ui->label_emailCheck->setStyleSheet("");
        ui->lineEdit_email->setStyleSheet("");
    }
}

//保存密码
void Index::on_pushButton_savePwd_clicked()
{
    if(!ui->label_oldPwdCheck->text().isEmpty() || !ui->label_newPwdCheck->text().isEmpty() || !ui->label_newPwd2Check->text().isEmpty()
            || ui->lineEdit_oldPwd->text().isEmpty() || ui->lineEdit_newPwd->text().isEmpty() || ui->lineEdit_newPwd2->text().isEmpty()){
        return;
    }
    QNetworkReply *reply = userApi.updatePwd(ui->lineEdit_oldPwd->text(),ui->lineEdit_newPwd2->text());
    QByteArray bytes = reply->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(this,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    QMessageBox::warning(this,"提示",obj.value("msg").toString());
}

//密码检测
void Index::on_lineEdit_oldPwd_textChanged(const QString &arg1)
{
    if(arg1.isEmpty()){
         ui->label_oldPwdCheck->setText("旧密码不能为空");
         ui->label_oldPwdCheck->setStyleSheet("color:red;");
         ui->lineEdit_oldPwd->setStyleSheet("border:1px solid red;");
    }else{
         ui->label_oldPwdCheck->setText("");
         ui->lineEdit_oldPwd->setStyleSheet("");
         ui->label_oldPwdCheck->setStyleSheet("");
    }
}

//密码检测
void Index::on_lineEdit_newPwd_textChanged(const QString &arg1)
{
    if(arg1.isEmpty()){
         ui->lineEdit_newPwd->setStyleSheet("border:1px solid red");
         ui->label_newPwdCheck->setText("旧密码不能为空");
         ui->label_newPwdCheck->setStyleSheet("color:red;");
    }else if(arg1.length() < 6 || arg1.length() > 20){
         ui->lineEdit_newPwd->setStyleSheet("border:1px solid red");
         ui->label_newPwdCheck->setText("长度在 6 到 20 个字符");
         ui->label_newPwdCheck->setStyleSheet("color:red;");
    }else if(arg1 == ui->lineEdit_newPwd2->text()){
         ui->lineEdit_newPwd2->setStyleSheet("");
         ui->label_newPwd2Check->setText("");
         ui->label_newPwd2Check->setStyleSheet("");
    }else{
         ui->lineEdit_newPwd->setStyleSheet("");
         ui->label_newPwdCheck->setText("");
         ui->label_newPwdCheck->setStyleSheet("");
    }
}

//密码检测
void Index::on_lineEdit_newPwd2_textChanged(const QString &arg1)
{
    if(arg1.isEmpty()){
         ui->lineEdit_newPwd2->setStyleSheet("border:1px solid red");
         ui->label_newPwd2Check->setText("确认密码不能为空");
         ui->label_newPwd2Check->setStyleSheet("color:red;");
    }else if(arg1 != ui->lineEdit_newPwd->text()){
         ui->lineEdit_newPwd2->setStyleSheet("border:1px solid red");
         ui->label_newPwd2Check->setText("两次输入的密码不一致");
         ui->label_newPwd2Check->setStyleSheet("color:red;");
    }else{
         ui->lineEdit_newPwd2->setStyleSheet("");
         ui->label_newPwd2Check->setText("");
         ui->label_newPwd2Check->setStyleSheet("");
    }
}

//切换菜单模式按钮
void Index::on_pushButton_hideRouter_clicked()
{
    ui->treeWidget->clear();
    if(ui->label_title->width() == 60){
        ui->label_title->setMaximumWidth(180);
        ui->label_title->setText("若依管理系统");
        ui->treeWidget->setMaximumWidth(180);
        setRouters(routerArr);
    }else{
        ui->label_title->setMaximumWidth(60);
        ui->label_title->setPixmap(QPixmap(":/image/res/museum.ico").scaled(40,40));
        ui->treeWidget->setMaximumWidth(60);
        for(int i = 0;i< routerArr.size();i++){
            QJsonObject menu = routerArr.at(i).toObject();
            QTreeWidgetItem * menuTitle = new QTreeWidgetItem(ui->treeWidget);
            menuTitle->setIcon(0,QIcon(":/image/res/" + menu.value("name").toString().toLower() + ".ico"));
            menuTitle->setText(0,"    " + QString::number(i+1));
            ui->treeWidget->setStyleSheet("font: 12pt 黑体;border:none;color:white;");
        }
    }
}

//弹出小路由菜单
void Index::popMenu(int flag)
{
    treeWidget->clear();
    QJsonObject menu = routerArr.at(flag).toObject();
    QJsonArray menuChildren = menu.value("children").toArray();
    for(int j = 0;j< menuChildren.size();j++){
        QJsonObject menuChild = menuChildren.at(j).toObject();
        QTreeWidgetItem * menuChildTitle = new QTreeWidgetItem(treeWidget,
            QStringList(menuChild.value("meta").toObject().value("title").toString()));
        QJsonArray menuGrandsons = menuChild.value("children").toArray();
        setTreeRouters(&menuGrandsons,menuChildTitle);
    }
}

//点击菜单跳转页面
void Index::routerJump(QTreeWidgetItem *item)
{
    if(item->text(0) == "用户管理"){
        if(ui->stackedWidget->currentIndex() == 1){
            return;
        }
        ui->label_location->setText("系统管理/用户管理");
        ui->stackedWidget->setCurrentIndex(32);
        ui->treeWidget->setEnabled(0);
        initUserManager();
        ui->stackedWidget->setCurrentIndex(1);
        ui->treeWidget->setEnabled(1);
    }else if(item->text(0) == "角色管理"){
        if(ui->stackedWidget->currentIndex() == 2){
            return;
        }
        ui->treeWidget->setEnabled(0);
        ui->label_location->setText("系统管理/角色管理");
        ui->stackedWidget->setCurrentIndex(32);
        if(routerObj != nullptr){
            delete routerObj;
        }
        routerObj = new RoleManager(ui);
        ui->stackedWidget->setCurrentIndex(2);
        ui->treeWidget->setEnabled(1);
    }else if(item->text(0) == "菜单管理"){
        if(ui->stackedWidget->currentIndex() == 3){
            return;
        }
        ui->treeWidget->setEnabled(0);
        ui->label_location->setText("系统管理/菜单管理");
        ui->stackedWidget->setCurrentIndex(32);
        if(routerObj != nullptr){
            delete routerObj;
        }
        routerObj = new MenuManager(ui);
        ui->stackedWidget->setCurrentIndex(3);
        ui->treeWidget->setEnabled(1);
    }else if(item->text(0) == "字典管理"){
        if(ui->stackedWidget->currentIndex() == 4){
            return;
        }
        ui->treeWidget->setEnabled(0);
        ui->label_location->setText("系统管理/字典管理");
        ui->stackedWidget->setCurrentIndex(32);
        if(routerObj != nullptr){
            delete routerObj;
        }
        routerObj = new DictionaryManager(ui);
        ui->stackedWidget->setCurrentIndex(4);
        ui->treeWidget->setEnabled(1);
    }else if(item->text(0) == "参数设置"){
        if(ui->stackedWidget->currentIndex() == 5){
            return;
        }
        ui->stackedWidget->setCurrentIndex(32);
        ui->treeWidget->setEnabled(0);
        if(routerObj != nullptr){
            delete routerObj;
        }
        routerObj = new ParamsSet(ui);
        ui->stackedWidget->setCurrentIndex(5);
        ui->treeWidget->setEnabled(1);
        ui->label_location->setText("系统管理/参数设置");
    }else if(item->text(0) == "通知公告"){
        if(ui->stackedWidget->currentIndex() == 6){
            return;
        }
        ui->stackedWidget->setCurrentIndex(6);
        ui->label_location->setText("系统管理/通知公告");
    }else if(item->text(0) == "操作日志"){
        if(ui->stackedWidget->currentIndex() == 7){
            return;
        }
        ui->stackedWidget->setCurrentIndex(7);
        ui->label_location->setText("系统管理/操作日志");
    }else if(item->text(0) == "登录日志"){
        if(ui->stackedWidget->currentIndex() == 8){
            return;
        }
        ui->stackedWidget->setCurrentIndex(8);
        ui->label_location->setText("系统管理/登录日志");
    }else if(item->text(0) == "在线用户"){
        if(ui->stackedWidget->currentIndex() == 9){
            return;
        }
        ui->stackedWidget->setCurrentIndex(9);
        ui->label_location->setText("系统监控/在线用户");
    }else if(item->text(0) == "定时任务"){
        if(ui->stackedWidget->currentIndex() == 10){
            return;
        }
        ui->stackedWidget->setCurrentIndex(10);
        ui->label_location->setText("系统监控/定时任务");
    }else if(item->text(0) == "数据监控"){
        if(ui->stackedWidget->currentIndex() == 11){
            return;
        }
        ui->stackedWidget->setCurrentIndex(11);
        ui->label_location->setText("系统监控/数据监控");
    }else if(item->text(0) == "服务监控"){
        if(ui->stackedWidget->currentIndex() == 12){
            return;
        }
        ui->stackedWidget->setCurrentIndex(32);
        ui->treeWidget->setEnabled(0);
        ServerMonitor s(ui);
        s.init();
        ui->stackedWidget->setCurrentIndex(12);
        ui->treeWidget->setEnabled(1);
        ui->label_location->setText("系统监控/服务监控");
    }else if(item->text(0) == "缓存监控"){
        if(ui->stackedWidget->currentIndex() == 13){
            return;
        }
        ui->label_location->setText("系统监控/缓存监控");

        ui->stackedWidget->setCurrentIndex(13);    
    }else if(item->text(0) == "缓存列表"){
        if(ui->stackedWidget->currentIndex() == 14){
            return;
        }
        ui->stackedWidget->setCurrentIndex(14);
        ui->label_location->setText("系统监控/缓存列表");
    }else if(item->text(0) == "表单构建"){
        if(ui->stackedWidget->currentIndex() == 15){
            return;
        }
        ui->stackedWidget->setCurrentIndex(15);
        ui->label_location->setText("系统工具/表单构建");
    }else if(item->text(0) == "代码生成"){
        if(ui->stackedWidget->currentIndex() == 16){
            return;
        }
        ui->stackedWidget->setCurrentIndex(16);
        ui->label_location->setText("系统工具/代码生成");
    }else if(item->text(0) == "系统接口"){
        if(ui->stackedWidget->currentIndex() == 17){
            return;
        }
        ui->stackedWidget->setCurrentIndex(17);
        ui->label_location->setText("系统工具/系统接口");
    }else if(item->text(0) == "预约管理"){
        if(ui->stackedWidget->currentIndex() == 18){
            return;
        }
        ui->stackedWidget->setCurrentIndex(18);
        ui->label_location->setText("博物馆管理/预约管理");
    }else if(item->text(0) == "轮播图管理"){
        if(ui->stackedWidget->currentIndex() == 19){
            return;
        }
        ui->stackedWidget->setCurrentIndex(19);
        ui->label_location->setText("博物馆管理/轮播图管理");
    }else if(item->text(0) == "分类管理"){
        ui->label_location->setText("博物馆管理/藏品信息/分类管理");
        if(ui->stackedWidget->currentIndex() == 20){
            return;
        }
        ui->stackedWidget->setCurrentIndex(20);
    }else if(item->text(0) == "属性管理"){
        if(ui->stackedWidget->currentIndex() == 21){
            return;
        }
        ui->stackedWidget->setCurrentIndex(21);
        ui->label_location->setText("博物馆管理/藏品信息/属性管理");
    }else if(item->text(0) == "藏品管理"){
        if(ui->stackedWidget->currentIndex() == 22){
            return;
        }
        ui->stackedWidget->setCurrentIndex(22);
        ui->label_location->setText("博物馆管理/藏品信息/藏品管理");
    }else if(item->text(0) == "藏品上架"){
        if(ui->stackedWidget->currentIndex() == 23){
            return;
        }
        ui->stackedWidget->setCurrentIndex(23);
        ui->label_location->setText("博物馆管理/藏品信息/藏品上架");
    }else if(item->text(0) == "订单管理"){
        if(ui->stackedWidget->currentIndex() == 24){
            return;
        }
        ui->stackedWidget->setCurrentIndex(24);
        ui->label_location->setText("博物馆管理/订单管理");
    }else if(item->text(0) == "留言管理"){
        if(ui->stackedWidget->currentIndex() == 25){
            return;
        }
        ui->stackedWidget->setCurrentIndex(25);
        ui->label_location->setText("博物馆管理/留言管理");
    }else if(item->text(0) == "发布活动"){
        if(ui->stackedWidget->currentIndex() == 26){
            return;
        }
        ui->stackedWidget->setCurrentIndex(26);
        ui->label_location->setText("博物馆管理/活动信息/发布活动");
    }else if(item->text(0) == "活动管理"){
        if(ui->stackedWidget->currentIndex() == 27){
            return;
        }
        ui->stackedWidget->setCurrentIndex(27);
        ui->label_location->setText("博物馆管理/活动信息/活动管理");
    }else if(item->text(0) == "图片管理"){
        if(ui->stackedWidget->currentIndex() == 28){
            return;
        }
        ui->stackedWidget->setCurrentIndex(28);
        ui->label_location->setText("博物馆管理/活动信息/图片管理");
    }else if(item->text(0) == "活动预约"){
        if(ui->stackedWidget->currentIndex() == 29){
            return;
        }
        ui->stackedWidget->setCurrentIndex(29);
        ui->label_location->setText("博物馆管理/活动信息/活动预约");
    }else if(item->text(0) == "发布公告"){
        if(ui->stackedWidget->currentIndex() == 30){
            return;
        }
        ui->stackedWidget->setCurrentIndex(30);
        ui->label_location->setText("博物馆管理/发布公告");
    }else if(item->text(0) == "公告管理"){
        if(ui->stackedWidget->currentIndex() == 31){
            return;
        }
        ui->stackedWidget->setCurrentIndex(31);
        ui->label_location->setText("博物馆管理/公告管理");
    }else if(item->text(0) == "部门管理"){
        if(ui->stackedWidget->currentIndex() == 33){
            return;
        }
        ui->treeWidget->setEnabled(0);
        ui->label_location->setText("系统管理/部门管理");
        ui->stackedWidget->setCurrentIndex(32);
        if(routerObj != nullptr){
            delete routerObj;
        }
        routerObj = new DeptManager(ui);
        ui->stackedWidget->setCurrentIndex(33);
        ui->treeWidget->setEnabled(1);
    }else if(item->text(0) == "岗位管理"){
        if(ui->stackedWidget->currentIndex() == 34){
            return;
        }
        ui->stackedWidget->setCurrentIndex(34);
        ui->label_location->setText("系统管理/岗位管理");
    }else if(item->text(0) == "    1"){
        popMenu(0);
        treeWidget->move(ui->label_title->mapToGlobal(QPoint(0,0)).x() + 60,
                            ui->label_title->mapToGlobal(QPoint(0,0)).y() + 80);
        treeWidget->show();
    }else if(item->text(0) == "    2"){
        popMenu(1);
        treeWidget->move(ui->label_title->mapToGlobal(QPoint(0,0)).x() + 60,
                            ui->label_title->mapToGlobal(QPoint(0,0)).y() + 100);
        treeWidget->show();
    }else if(item->text(0) == "    3"){
        popMenu(2);
        treeWidget->move(ui->label_title->mapToGlobal(QPoint(0,0)).x() + 60,
                            ui->label_title->mapToGlobal(QPoint(0,0)).y() + 120);
        treeWidget->show();
    }else if(item->text(0) == "    4"){
        popMenu(3);
        treeWidget->move(ui->label_title->mapToGlobal(QPoint(0,0)).x() + 60,
                            ui->label_title->mapToGlobal(QPoint(0,0)).y() + 140);
        treeWidget->show();
    }
}

//初始化用户管理
void Index::initUserManager()
{
    userManagerCurrentPage = 1;
    userManagerDeptId = 0;
    disconnect(connection);
    ui->treeWidget_2->clear();
    ui->comboBox_userManager_status->clear();

    //状态
    QNetworkReply *statusReply = userManagerApi.sys_normal_disable();
    dictDataList = userManager.getDictData(statusReply);
    if(dictDataList == nullptr){
        QMessageBox::warning(0,"提示","状态字典查询为空");
        return;
    }
    ui->comboBox_userManager_status->addItems(QStringList(""));
    for(DictData dict : *dictDataList){
        ui->comboBox_userManager_status->addItems(QStringList(dict.dictLabel));
    }

    //性别
    QNetworkReply *sexReply = userManagerApi.sys_user_sex();
    sexDataList = userManager.getDictData(sexReply);
    if(dictDataList == nullptr){
        QMessageBox::warning(0,"提示","性别字典查询为空");
        return;
    }

    //部门树
    deptTreeList = userManager.getTreeSelect();
    if(deptTreeList == nullptr){
        QMessageBox::warning(0,"提示","部门树查询为空");
        return;
    }
    for(int i = 0;i< deptTreeList->size();i++){
        QTreeWidgetItem *menu = new QTreeWidgetItem(ui->treeWidget_2,
            QStringList(deptTreeList->at(i).label));
        QList<TreeSelect> list = deptTreeList->at(i).children;
        menu->setData(1,0,deptTreeList->at(i).id);
        setTreeMenu(&list,menu);
    }
    //部门树点击事件
    connection =connect(ui->treeWidget_2,&QTreeWidget::clicked,this,[=]{
        userManagerDeptId = ui->treeWidget_2->currentItem()->data(1,0).value<int>();
        setUserManagerPage(userManagerCurrentPage,userManagerPageSize);
    });

    //用户列表
    setUserManagerPage(1,10);
}

//部门树
void Index::setTreeMenu(QList<TreeSelect> *treeList, QTreeWidgetItem *menu)
{
    for(int i = 0;i< treeList->size();i++){
        QTreeWidgetItem *childmenu = new QTreeWidgetItem(menu,
            QStringList(treeList->at(i).label));
        QList<TreeSelect> l = treeList->at(i).children;
        childmenu->setData(1,0,treeList->at(i).id);
        setTreeMenu(&l,childmenu);
    }
    ui->treeWidget_2->expandAll();
}

//每页大小
void Index::on_comboBox_userManager_pageItem_currentIndexChanged(int index)
{
    switch (index) {
    case 0:
        userManagerPageSize = 5;
        break;
    case 1:
        userManagerPageSize = 10;
        break;
    case 2:
        userManagerPageSize = 20;
        break;
    case 3:
        userManagerPageSize = 50;
        break;
    case 4:
        userManagerPageSize = 100;
        break;
    default:
        userManagerPageSize = 10;
        break;
    }
    userManagerCurrentPage = 1;
    ui->label_userManager_currentPage->setText(QString::number(userManagerCurrentPage));
    setUserManagerPage(1,userManagerPageSize);
}

//下一页
void Index::on_btn_userManager_next_clicked()
{
    ui->btn_userManager_next->setEnabled(0);
    userManagerCurrentPage += 1;
    ui->btn_userManager_pervious->setEnabled(1);
    ui->label_userManager_currentPage->setText(QString::number(userManagerCurrentPage));

    setUserManagerPage(userManagerCurrentPage,userManagerPageSize);
}

//上一页
void Index::on_btn_userManager_pervious_clicked()
{
    ui->btn_userManager_pervious->setEnabled(0);
    userManagerCurrentPage -= 1;
    ui->label_userManager_currentPage->setText(QString::number(userManagerCurrentPage));

    setUserManagerPage(userManagerCurrentPage,userManagerPageSize);
}

//跳转第几页
void Index::on_lineEdit_userManager_gotoPage_returnPressed()
{
    int totalPage = userManagerTotal / userManagerPageSize + 1;
    int linePage = ui->lineEdit_userManager_gotoPage->text().toInt();
    if(totalPage < linePage){
        return;
    }
    ui->lineEdit_userManager_gotoPage->clear();
    userManagerCurrentPage = linePage;
    ui->label_userManager_currentPage->setText(QString::number(userManagerCurrentPage));
    setUserManagerPage(linePage,userManagerPageSize);
}

//设置用户列表
void Index::setUserManagerPage(int pageNum,int pageSize)
{
    QString status= "";
    if(ui->comboBox_userManager_status->currentText() == "正常"){
        status = "0";
    }else if(ui->comboBox_userManager_status->currentText() == "停用"){
        status = "1";
    }
    QNetworkReply *reply = userManagerApi.list(pageNum,pageSize,
                                               userManagerDeptId,
        ui->lineEdit_userManager_username->text(),
        ui->lineEdit_userManager_phone->text(),
        status,
        ui->dateEdit_userManager_startTime->text(),
        ui->dateEdit_userManager_endTime->text());
    QByteArray bytes = reply->readAll();
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    if(obj.value("code").toInt() != 200){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        return;
    }
    userManagerTotal = obj.value("total").toInt();
    ui->label_userManager_count->setText("共"+QString::number(userManagerTotal)+"条");
    ui->label_userManager_currentPage->setText(QString::number(userManagerCurrentPage));
    if((userManagerTotal - userManagerPageSize * userManagerCurrentPage) < 1){
        ui->btn_userManager_next->setEnabled(0);
    }else{
        ui->btn_userManager_next->setEnabled(1);
    }
    QList<User> *userList = userManager.getList(obj);
    userManagerTableColumn.clear();
    userManagerTableColumn<<"序号"<<"用户名称"<<"用户昵称"<<"部门"<<"手机号码"<<"状态"<<"创建时间"<<"操作";
    utils.settableWidget_userManager(userList,ui->tableWidget_userManager,userManagerTableColumn);
    for(int i = 0;i< userList->size();i++){
        if(userList->at(i).userId != 1){
            QWidget *tmp_widget = new QWidget();
            QHBoxLayout *tmp_layout = new QHBoxLayout();
            QPushButton *btnUpdate = new QPushButton;
            QPushButton *btnDelete = new QPushButton;
            QPushButton *btnMore = new QPushButton;
            btnUpdate->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(231, 250, 240);color: black;}QPushButton:hover {background-color: rgb(19, 206, 102);}QPushButton:pressed {background-color: rgb(19, 150, 102);}");
            btnDelete->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(232, 244, 255);color: black;}QPushButton:hover {background-color: rgb(24, 144, 255);}QPushButton:pressed {background-color: rgb(24, 144, 200);}");
            btnMore->setStyleSheet  ("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(255, 237, 237);color: black;}QPushButton:hover {background-color: rgb(255, 73, 73);}QPushButton:pressed {background-color: rgb(200, 73, 73);}");
            connect(btnDelete,&QPushButton::clicked,this,[=](){
                int flag = QMessageBox::question(0,"提示","确定删除该用户吗?",QMessageBox::No | QMessageBox::Yes);
                if(flag == QMessageBox::No){
                    return;
                }
                QNetworkReply *reply = userManagerApi.deleteUserByIds(QString::number(userList->at(i).userId));
                QByteArray bytes = reply->readAll().data();
                if(bytes.isEmpty()){
                    QMessageBox::warning(this,"提示","服务器连接失败");
                    return;
                }
                QJsonObject obj = QJsonDocument::fromJson(bytes).object();
                QMessageBox::warning(this,"提示",obj.value("msg").toString());
                if(200 != obj.value("code").toInt()){
                    return;
                }
                setUserManagerPage(userManagerCurrentPage,userManagerPageSize);
            });
            connect(btnUpdate,&QPushButton::clicked,this,[=](){
                EditUserDlg edituserdlg(userList->at(i).userId);
                connect(this,&Index::sendParamToEditUserDlg,&edituserdlg,&EditUserDlg::getParam);
                connect(&edituserdlg,&EditUserDlg::addSuccess,this,&Index::on_btn_userManager_refresh_clicked);
                emit sendParamToEditUserDlg(deptTreeList,
                                            initPassword,
                                            dictDataList,
                                            sexDataList);
                edituserdlg.exec();
            });
            connect(btnMore,&QPushButton::clicked,this,[=](){
                //更多按钮弹窗相关
                //更多按钮相关
                moreDlg = new QDialog;
                QVBoxLayout *l = new QVBoxLayout(moreDlg);
                moreDlg->setWindowFlag(Qt::FramelessWindowHint);
                QPushButton *resetPwd = new QPushButton;
                QPushButton *divideRole = new QPushButton;
                resetPwd->setText("重置密码");
                divideRole->setText("分配角色");
                l->addWidget(resetPwd);
                l->addWidget(divideRole);
                moreDlg->move(btnMore->mapToGlobal(QPoint(0,0)).x(),
                            btnMore->mapToGlobal(QPoint(0,0)).y() + 25);
                moreDlg->show();
                connect(resetPwd,&QPushButton::clicked,this,[=](){
                    moreDlg->close();
                    QDialog *d = new QDialog;
                    d->setWindowTitle("重置密码");
                    d->setFixedSize(420,206);
                    QLabel label;
                    label.setParent(d);
                    label.setFixedHeight(30);
                    label.setText("请输入【" + userList->at(i).userName + "】的新密码");
                    label.move(d->mapToGlobal(QPoint(0,0)).x() + 20,
                               d->mapToGlobal(QPoint(0,0)).y() + 25);
                    QLineEdit *l = new QLineEdit;;
                    l->setFixedSize(388,36);
                    l->setParent(d);
                    l->move(d->mapToGlobal(QPoint(0,0)).x() + 20,
                           d->mapToGlobal(QPoint(0,0)).y() + 60);
                    QLabel *tip = new QLabel;
                    tip->setParent(d);
                    tip->setMinimumWidth(250);
                    tip->setStyleSheet("color:red;");
                    tip->move(d->mapToGlobal(QPoint(0,0)).x() + 20,
                               d->mapToGlobal(QPoint(0,0)).y() + 95);
                    QPushButton ok;
                    ok.setFixedSize(55,35);
                    ok.setParent(d);
                    ok.setText("确定");
                    ok.move(d->mapToGlobal(QPoint(0,0)).x() + 350,
                             d->mapToGlobal(QPoint(0,0)).y() + 130);
                    QPushButton no;
                    no.setParent(d);
                    no.setText("取消");
                    no.setFixedSize(55,35);
                    no.move(d->mapToGlobal(QPoint(0,0)).x() + 285,
                             d->mapToGlobal(QPoint(0,0)).y() + 130);
                    connect(&no,&QPushButton::clicked,this,[=](){
                        d->close();
                    });
                    connect(&ok,&QPushButton::clicked,this,[=](){
                        if(l->text().length() < 5){
                            tip->setText("用户密码长度必须介于 5 和 20 之间");
                            l->setStyleSheet("border:1px solid red;");
                            return;
                        }else{
                            QNetworkReply *reply = userManagerApi.resetPwd(l->text(),QString::number(userList->at(i).userId));
                            QByteArray bytes = reply->readAll().data();
                            if(bytes.isEmpty()){
                                QMessageBox::warning(this,"提示","服务器连接失败");
                                return;
                            }
                            QJsonObject obj = QJsonDocument::fromJson(bytes).object();
                            d->close();
                            QMessageBox::warning(this,"提示",obj.value("msg").toString());
                        }
                    });
                    connect(l,&QLineEdit::textChanged,this,[=](){
                        if(l->text().length() < 5){
                            tip->setText("用户密码长度必须介于 5 和 20 之间");
                            l->setStyleSheet("border:1px solid red;");
                        }else{
                            tip->setText("");
                            l->setStyleSheet("");
                        }
                    });
                    d->exec();
                });
                connect(divideRole,&QPushButton::clicked,this,[=](){
                    moreDlg->close();
                    AuthRoleDlg authRoleDlg(userList->at(i).userId);
                    authRoleDlg.exec();
                });
            });
            btnMore->setText("》更多");
            btnDelete->setText("🗑删除");
            btnUpdate->setText("🖍修改");
            tmp_layout->addWidget(btnUpdate);
            tmp_layout->addWidget(btnDelete);
            tmp_layout->addWidget(btnMore);
            tmp_widget->setLayout(tmp_layout);
            tmp_layout->setMargin(0);
            ui->tableWidget_userManager->setCellWidget(i,7,tmp_widget);
        }
    }
    ui->btn_userManager_pervious->setEnabled(1);
    if(userManagerCurrentPage == 1){
        ui->btn_userManager_pervious->setEnabled(0);
        return;
    }
}

//隐藏搜索
void Index::on_btn_userManager_hideSearch_clicked()
{
    ui->widget_3->setHidden(! ui->widget_3->isHidden());
}

//刷新列表
void Index::on_btn_userManager_refresh_clicked()
{
    userManagerDeptId = 0;
    setUserManagerPage(userManagerCurrentPage,userManagerPageSize);
}

//搜索
void Index::on_btn_userManager_search_clicked()
{
    setUserManagerPage(userManagerCurrentPage,userManagerPageSize);
}

//重置搜索条件
void Index::on_btn_userManager_reset_clicked()
{
    ui->lineEdit_userManager_username->clear();
    ui->lineEdit_userManager_phone->clear();
    ui->comboBox_userManager_status->setCurrentIndex(0);
    ui->dateEdit_userManager_endTime->setDate(QDate(2000,1,1));
    ui->dateEdit_userManager_startTime->setDate(QDate(2000,1,1));
    userManagerDeptId = 0;
    setUserManagerPage(1,10);
}

//部门树过滤
void Index::on_lineEdit_userManager_deptName_textChanged(const QString &arg1)
{
    int items = ui->treeWidget_2->topLevelItemCount();
    for(int i = 0;i< items;i++){
        QTreeWidgetItem *treeWidget = ui->treeWidget_2->topLevelItem(i);
        utils.filterTreeWidget(treeWidget,arg1);
    }
}

//隐藏列
void Index::on_btn_userManager_isHideColumn_clicked()
{
    userManagerHideColumnDlg->show();
}


void Index::on_btn_userManager_add_clicked()
{
    EditUserDlg edituserdlg(-5);
    connect(this,&Index::sendParamToEditUserDlg,&edituserdlg,&EditUserDlg::getParam);
    connect(&edituserdlg,&EditUserDlg::addSuccess,this,&Index::on_btn_userManager_refresh_clicked);
    emit sendParamToEditUserDlg(deptTreeList,
                                initPassword,
                                dictDataList,
                                sexDataList);
    edituserdlg.exec();
}


void Index::on_btn_userManager_modify_clicked()
{
    QList<QTableWidgetItem*> items = ui->tableWidget_userManager->selectedItems();
    if(items.size() / 6 != 1){
        return;
    }
    EditUserDlg edituserdlg(items.at(0)->text().toInt());
    connect(this,&Index::sendParamToEditUserDlg,&edituserdlg,&EditUserDlg::getParam);
    connect(&edituserdlg,&EditUserDlg::addSuccess,this,&Index::on_btn_userManager_refresh_clicked);
    emit sendParamToEditUserDlg(deptTreeList,
                                initPassword,
                                dictDataList,
                                sexDataList);
    edituserdlg.exec();
}


void Index::on_btn_userManager_delete_clicked()
{
    QList<QTableWidgetItem*> items = ui->tableWidget_userManager->selectedItems();
    if(items.size() == 0) return;
    int rowCount = items.size() / 6;
    QString ids;
    for(int i = 0;i< rowCount;i++){
        int row = ui->tableWidget_userManager->row(items.at(i * 6));
        if(i != rowCount - 1){
            ids += ui->tableWidget_userManager->item(row,0)->text() +",";
        }else{
            ids += ui->tableWidget_userManager->item(row,0)->text();
        }
    }
    int flag = QMessageBox::question(0,"提示","确定删除所选用户吗？",QMessageBox::Yes|QMessageBox::No);
    if(flag == QMessageBox::No){
        return;
    }
    QNetworkReply *reply = userManagerApi.deleteUserByIds(ids);
    QByteArray bytes = reply->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(this,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    QMessageBox::warning(this,"提示",obj.value("msg").toString());
    if(200 != obj.value("code").toInt()){
        return;
    }
    setUserManagerPage(userManagerCurrentPage,userManagerPageSize);
}


void Index::on_btn_userManager_export_clicked()
{
    utils.exportExcel(ui->tableWidget_userManager,"测试");
}


void Index::on_btn_userManager_import_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(this,"选择文件",
        QCoreApplication::applicationDirPath(),tr("Excel (*.xlsx *.xls"));
    if(filePath.isEmpty()) return;
    QNetworkReply *r = utils.uploadFile(filePath,Config::baseUrl + "system/user/importData?updateSupport=0");
    QByteArray bytes = r->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(this,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    QMessageBox::warning(this,"提示",obj.value("msg").toString());
    setUserManagerPage(userManagerCurrentPage,userManagerPageSize);
}


